var qdd_host = window.location.host || '';
var debug = false;

if(!qdd_host || ['localhost','127.0'].indexOf(qdd_host) >= 0){
    qdd_host = '../';
    debug = true;
}else{
    qdd_host = '';
}


thin.imports('http://icdn.51hub.cn/static/axios/0.19.0/axios.min.js');

thin.use(function() {
    var self   = this;

    function getCookie (name) {
      var arr;
      var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
      if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
      else
        return null;
    }

    // 线路检测
    function checkUrl(){

        console.log("%c"+">>> 线路检测中...","color:green");
        
        axios({
            method: 'POST',
            url: "https://lotkl.kojo.club/api?console.ytt.urlCheck&_t="+Math.random(),
            data: {},
            timeout: 10000,
            headers: {}
        }).then(function(res){
            // console.dir(res)
            if(res.data && res.data.code == 201){
                var min = -1;
                var url = '';
                var data = res.data.data || {};
                for(var i in data){
                    console.log("%c"+">>> "+i + "  "+data[i]+"ms","color:green");
                    if(min == -1) min = Number(data[i]);
                    if(Number(data[i]) < min){
                        min = Number(data[i]);
                        url = i;
                    };
                }
                console.log("%c"+">>> 最优线路：" + url,"color:green");
                setReport(url)
            }else{
                console.log("线路检测失败")
                console.dir(res)
            }
        }).catch(function(err){
            // _catch("初始化失败 原因：",err)
            console.log("线路检测异常")
            console.dir(err)
        })
    }

	// 上报信息
	function setReport(url){
		var data_opt = {};
		if(debug){
			data_opt = {
				domain:'http://gf4.ttytcs25.com:86',
				cookie:'7f71a652a8e241206446023839eb6a8c',
			}
		}else{
			data_opt = {
				domain:url,
				cookie:"LoginSessionID="+getCookie("LoginSessionID"),
			}
		}
		axios({
			method: 'POST',
			// url: "https://lotkl.kojo.club/api?console.ytt.init&_t="+Math.random(),
            url: (debug ? "http://iter.io":"https://lotkl.kojo.club") + "/api?console.ytt.init&_t="+Math.random(),
			data: data_opt,
			timeout: 5000,
			headers: {}
		}).then(function(res){
			if(res.data && res.data.code == 201){
				console.log("%c"+">>> 初始化成功,可以正常启动挂机！","color:green")
			}else{
				_catch("初始化异常  异常原因：",res)
			}
		}).catch(function(err){
			_catch("初始化失败 原因：",err)
		})
	}

	function _catch(text,err){
		console.log(text)
		console.dir(err)
		console.dir("5秒后重新初始化")
		var tim = 5;
		var timer = setInterval(function(){
            if(tim <= 0){
            	console.dir("开始重新初始化...")
            	clearInterval(timer);
                setReport()
                return false;
            }
            tim -= 1;
            console.dir("准备重新初始化："+tim)
		},1000)
	}
    checkUrl();
    
});